<template>
  <div>
    <el-upload :action="minioUploadUrl" list-type="picture-card" :file-list="fileList" :before-upload="beforeUpload" :on-remove="handleRemove" :on-success="handleUploadSuccess" :on-preview="handlePreview" :limit="maxCount" :on-exceed="handleExceed">
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog v-model="dataObj.dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>
<script setup>
import { reactive, ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
const props = defineProps({
  value: {
    type: Array
  },
  maxCount: {
    type: Number,
    default: 5
  }
})

let state = reactive(props.value)

let dataObj = reactive({
  policy: '',
  signature: '',
  key: '',
  ossaccessKeyId: '',
  dir: '',
  host: '',
  dialogVisible: false
})

const dialogImageUrl = ref('')
const useOss = ref(false)
const minioUploadUrl = ref('http://localhost:8080/minio/upload')

const fileList = computed(() => {
  let fileList = []
  if (state != null && state != undefined) {
    for (let i = 0; i < state.length; i++) {
      fileList.push({ url: state[i] })
    }
  }
  return fileList
})

const emits = defineEmits(['uploadImage'])

function emitInput(fileList) {
  let value = []
  for (let i = 0; i < fileList.length; i++) {
    value.push(fileList[i].url)
  }
  emits('uploadImage', value)
}
function handleRemove(file, fileList) {
  emitInput(fileList)
}
function handlePreview(file) {
  dataObj.dialogVisible = true
  dialogImageUrl.value = file.url
}
function beforeUpload() {
  if (!useOss.value) {
    //不使用oss不需要获取策略
    return true
  }
}
function handleUploadSuccess(res, file) {
  let url = dataObj.host + '/' + dataObj.dir + '/' + file.name
  if (!useOss.value) {
    //不使用oss直接获取图片路径
    url = res.data.url
  }
  fileList.value.push({ name: file.name, url: url })
  emitInput(fileList.value)
}
function handleExceed() {
  ElMessage({
    message: '最多只能上传' + state.maxCount + '张图片',
    type: 'warning',
    duration: 1000
  })
}
</script>
<style></style>
